import React, { Component } from 'react'
import Child from '../Child'
import './index.css'

class Parent extends Component {
  state = {
    list: [
      {
        id: 1,
        name: '超级好吃的棒棒糖',
        price: 18.8,
        info: '开业大酬宾，全场8折',
      },
      {
        id: 2,
        name: '超级好吃的大鸡腿',
        price: 34.2,
        info: '开业大酬宾，全场8折',
      },
      {
        id: 3,
        name: '超级无敌的冰激凌',
        price: 14.2,
        info: '开业大酬宾，全场8折',
      },
    ],
  }

  // !#1 父组件准备一个方法并传递给子组件
  changePrice = (id, price) => {
    // !#3 父组件接收参数并做修改
    this.setState({
      list: this.state.list.map((item) => {
        if (item.id === id) {
          let p = item.price - price
          if (p <= 0) {
            p = 0
          }
          return {
            ...item,
            // toFixed 返回是一个字符串
            // 做相减操作的时候没有问题，会有隐式转化，万一后续有相加操作呢就会出事啦
            // price: p.toFixed(2),
            price: p,
          }
        } else {
          return item
        }
      }),
    })
  }
  render() {
    return (
      <div className='parent'>
        {this.state.list.map((item) => (
          <Child key={item.id} {...item} changePrice={this.changePrice} />
        ))}
      </div>
    )
  }
}

export default Parent
